package client.material;

import client.common.dto.MaterialAddDTO;
import client.common.dto.MaterialPageReqDTO;
import client.common.result.MaterialPageResult;
import client.common.result.emun.ResultCodeEnum;
import client.common.vo.MaterialVO;
import client.material.button.ButtonEditor;
import client.material.button.ButtonRenderer;
import remote.common.content.MaterialPageContent;
import remote.service.MaterialService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.List;

public class MaterialArchiveQuery extends JFrame {
    
    private final MaterialService materialService = new MaterialService() {
    };
    private JTable dataTable;
    private JTextField searchTextField;
    private JComboBox<String> searchComboBox;
    private DefaultTableModel tableModel;
    private Integer currentPage = 1;
    private Integer pageSize = 17;
    private Integer totalPages = 1;
    // Pagination controls
    private JButton firstPageButton;
    private JButton prevPageButton;
    private JButton nextPageButton;
    private JButton lastPageButton;
    private JLabel pageInfoLabel;
    
    public MaterialArchiveQuery() {
        setTitle("物料档案查询");
        setSize(932, 600); // 初始大小
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        
        // 设置主布局为 BorderLayout
        setLayout(new BorderLayout(10, 10));
        
        // 创建并添加搜索面板
        JPanel searchPanel = createSearchPanel();
        add(searchPanel, BorderLayout.NORTH);
        
        // 创建并添加表格面板
        JPanel tablePanel = createTablePanel();
        add(tablePanel, BorderLayout.CENTER);
        
        // 创建并添加分页面板
        JPanel paginationPanel = createPaginationPanel();
        add(paginationPanel, BorderLayout.SOUTH);
        
        // 初始刷新表格
        freshTable();
        setVisible(true);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            MaterialArchiveQuery frame = new MaterialArchiveQuery();
            frame.setVisible(true);
        });
    }
    
    /**
     * 创建搜索面板
     */
    private JPanel createSearchPanel() {
        JPanel searchPanel = new JPanel();
        searchPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        searchPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        
        // 标签
        JLabel label = new JLabel("查询方式");
        label.setFont(label.getFont().deriveFont(20f));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(0, 0, 0, 10);
        searchPanel.add(label, gbc);
        
        // 搜索 ComboBox
        searchComboBox = new JComboBox<>(new String[]{"物料名称"});
        searchComboBox.setFont(searchComboBox.getFont().deriveFont(13f));
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0.2;
        searchPanel.add(searchComboBox, gbc);
        
        // 搜索 TextField
        searchTextField = new JTextField();
        searchTextField.setFont(searchTextField.getFont().deriveFont(15f));
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 0.5;
        gbc.insets = new Insets(0, 10, 0, 10);
        searchPanel.add(searchTextField, gbc);
        
        // 查询按钮
        JButton searchButton = new JButton("查询");
        searchButton.setPreferredSize(new Dimension(100, 30));
        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                currentPage = 1; // 重置为第一页
                String searchText = searchTextField.getText();
                String selectedQueryType = (String) searchComboBox.getSelectedItem();
                if ("物料名称".equals(selectedQueryType)) {
                    // 进行模糊查询
                    refreshTable(searchText); // 传递搜索文本进行模糊查询
                } else {
                    // 如果未选择有效的查询类型，可以选择不执行任何操作或弹出提示
                    JOptionPane.showMessageDialog(MaterialArchiveQuery.this, "请选择有效的查询方式", "警告", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        gbc.gridx = 3;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.NONE;
        gbc.weightx = 0;
        gbc.insets = new Insets(0, 10, 0, 5);
        searchPanel.add(searchButton, gbc);
        
        // 查询全部按钮
        JButton queryAllButton = new JButton("查询全部");
        queryAllButton.setPreferredSize(new Dimension(100, 30));
        queryAllButton.addActionListener(e -> {
            currentPage = 1; // 重置为第一页
            searchTextField.setText("");
            freshTable();
        });
        gbc.gridx = 4;
        gbc.gridy = 0;
        gbc.insets = new Insets(0, 5, 0, 0);
        searchPanel.add(queryAllButton, gbc);
        
        // 添加物料按钮
        JButton addMaterialButton = new JButton("添加物料");
        addMaterialButton.setPreferredSize(new Dimension(100, 30));
        addMaterialButton.addActionListener(e -> openAddMaterialDialog());
        gbc.gridx = 5;
        gbc.gridy = 0;
        gbc.insets = new Insets(0, 5, 0, 0);
        searchPanel.add(addMaterialButton, gbc);
        
        return searchPanel;
    }
    
    /**
     * 创建表格面板
     */
    private JPanel createTablePanel() {
        JPanel tablePanel = new JPanel(new BorderLayout());
        
        // 更新表格模型以包含物料ID列
        tableModel = new DefaultTableModel(new Object[]{"物料ID", "物料名称", "规格型号", "数量", "单位", "备注", "修改", "删除"}, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                // 仅“修改”和“删除”列可编辑
                return column == 6 || column == 7;
            }
        };
        
        // 表格
        dataTable = new JTable(tableModel);
        dataTable.setFillsViewportHeight(true);
        dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        dataTable.setFont(new Font("Serif", Font.PLAIN, 14));
        dataTable.setRowHeight(25);
        
        // 设置列渲染器和编辑器
        dataTable.getColumn("修改").setCellRenderer(new ButtonRenderer());
        dataTable.getColumn("修改").setCellEditor(new ButtonEditor(dataTable, true));
        dataTable.getColumn("删除").setCellRenderer(new ButtonRenderer());
        dataTable.getColumn("删除").setCellEditor(new ButtonEditor(dataTable, false));
        
        JScrollPane scrollPane = new JScrollPane(dataTable);
        tablePanel.add(scrollPane, BorderLayout.CENTER);
        
        return tablePanel;
    }
    
    /**
     * 创建分页面板
     */
    private JPanel createPaginationPanel() {
        JPanel paginationPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 10));
        
        // 首页按钮
        firstPageButton = new JButton("首页");
        firstPageButton.addActionListener(e -> {
            if (currentPage != 1) {
                currentPage = 1;
                freshTable();
            }
        });
        paginationPanel.add(firstPageButton);
        
        // 上一页按钮
        prevPageButton = new JButton("上一页");
        prevPageButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                freshTable();
            }
        });
        paginationPanel.add(prevPageButton);
        
        // 下一页按钮
        nextPageButton = new JButton("下一页");
        nextPageButton.addActionListener(e -> {
            if (currentPage < totalPages) {
                currentPage++;
                freshTable();
            }
        });
        paginationPanel.add(nextPageButton);
        
        // 末页按钮
        lastPageButton = new JButton("末页");
        lastPageButton.addActionListener(e -> {
            if (currentPage != totalPages) {
                currentPage = totalPages;
                freshTable();
            }
        });
        paginationPanel.add(lastPageButton);
        
        // 页码信息标签
        pageInfoLabel = new JLabel("第 1 页 / 共 1 页");
        pageInfoLabel.setFont(pageInfoLabel.getFont().deriveFont(14f));
        paginationPanel.add(pageInfoLabel);
        
        return paginationPanel;
    }
    
    /**
     * 重新请求接口，刷新表单
     */
    public void freshTable() {
        String searchType = (String) searchComboBox.getSelectedItem();
        String searchValue = searchTextField.getText().trim();
        
        // 调用远程服务获取分页数据
        MaterialPageResult materialByPage = materialService.getMaterialByPage(currentPage, pageSize, false);
        if (materialByPage == null || materialByPage.getData() == null) {
            JOptionPane.showMessageDialog(this, "获取数据失败", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        Integer total = materialByPage.getData().getTotal();
        List<MaterialVO> materialVOList = materialByPage.getData().getData();
        
        // 计算总页数
        totalPages = (int) Math.ceil((double) total / pageSize);
        if (totalPages == 0) totalPages = 1;
        
        // 更新页码显示
        pageInfoLabel.setText("第 " + currentPage + " 页 / 共 " + totalPages + " 页");
        
        // 更新分页按钮的状态
        firstPageButton.setEnabled(currentPage > 1);
        prevPageButton.setEnabled(currentPage > 1);
        nextPageButton.setEnabled(currentPage < totalPages);
        lastPageButton.setEnabled(currentPage < totalPages);
        
        // 清空当前表格数据
        tableModel.setRowCount(0);
        
        // 添加新数据到表格
        for (MaterialVO materialVO : materialVOList) {
            Object[] rowData = new Object[]{
                    materialVO.getId(), // 假设物料ID为Long类型，直接添加到表格中
                    materialVO.getName(),
                    materialVO.getSpecification(),
                    materialVO.getStock(),
                    materialVO.getUnit(),
                    materialVO.getRemark() != null ? materialVO.getRemark() : "",
                    "修改", // 操作列
                    "删除"  // 删除列
            };
            tableModel.addRow(rowData);
        }
    }
    
    public void refreshTable(String searchText) {
        // 创建 MaterialPageReqDTO 对象来处理分页请求参数
        MaterialPageReqDTO materialPageReqDTO = new MaterialPageReqDTO();
        materialPageReqDTO.setCurrent(currentPage);  // 当前页
        materialPageReqDTO.setSize(pageSize);        // 每页大小
        
        Object result; // 用于存储查询结果
        
        // 如果没有输入搜索文本，则弹出提示框
        if (searchText == null || searchText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入要查询的物料名称", "提示", JOptionPane.INFORMATION_MESSAGE);
            return; // 直接返回，避免继续执行
        }
        
        // 如果有搜索文本，则进行模糊查询
        if (searchText != null && !searchText.isEmpty()) {
            result = materialService.fuzzyQueryMaterial(searchText, 1, 10, false); // 进行模糊查询
        } else {
            // 如果没有搜索文本，则进行分页查询
            result = materialService.getMaterialByPage(materialPageReqDTO.getCurrent(), materialPageReqDTO.getSize(), true); // 传递分页参数
        }
        
        // 处理返回结果
        if (result instanceof MaterialPageResult) {
            MaterialPageResult pageResult = (MaterialPageResult) result;
            if (pageResult.getCode() == 200 && pageResult.getData() != null) {
                // 更新表格数据
                updateTableWithPageResult(pageResult);
            } else if (pageResult.getCode().equals(ResultCodeEnum.NO_PERMISSION.getCode())) {
                JOptionPane.showMessageDialog(this, pageResult.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, pageResult.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        } else {
            JOptionPane.showMessageDialog(this, "获取数据失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
    
    // 使用 MaterialPageResult 更新表格
    private void updateTableWithPageResult(MaterialPageResult pageResult) {
        MaterialPageContent pageContent = pageResult.getData();
        List<MaterialVO> materialVOList = pageContent.getData(); // 假设 MaterialPageContent 有 getRecords() 方法
        int total = pageContent.getTotal(); // 假设 MaterialPageContent 有 getTotal() 方法
        
        // 计算总页数
        totalPages = (int) Math.ceil((double) total / pageSize);
        if (totalPages == 0) totalPages = 1;
        
        // 更新页码显示
        pageInfoLabel.setText("第 " + currentPage + " 页 / 共 " + totalPages + " 页");
        
        // 更新分页按钮的状态
        firstPageButton.setEnabled(currentPage > 1);
        prevPageButton.setEnabled(currentPage > 1);
        nextPageButton.setEnabled(currentPage < totalPages);
        lastPageButton.setEnabled(currentPage < totalPages);
        
        // 清空当前表格数据
        tableModel.setRowCount(0);
        
        // 创建日期格式化对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        
        // 添加新数据到表格
        for (MaterialVO material : materialVOList) {
            tableModel.addRow(new Object[]{
                    material.getId(),
                    material.getName(),
                    material.getSpecification(),
                    material.getStock(),
                    material.getUnit(),
                    material.getRemark() != null ? material.getRemark() : "",
                    "修改",
                    "删除"
            });
        }
    }
    
    private void openAddMaterialDialog() {
        // 创建添加物料的对话框
        JDialog addMaterialDialog = new JDialog(this, "添加物料", true);
        addMaterialDialog.setSize(800, 500); // 对话框大小
        addMaterialDialog.setLocationRelativeTo(null); // 居中显示对话框
        addMaterialDialog.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10); // 添加间距
        
        // 背景色设置
        addMaterialDialog.getContentPane().setBackground(Color.decode("#F0F8FF"));
        
        // 字体设置
        Font labelFont = new Font("微软雅黑", Font.PLAIN, 16);
        Font textFieldFont = new Font("微软雅黑", Font.PLAIN, 16);
        
        // 物料名称输入
        JTextField nameField = createTextField();
        addComponent(gbc, 0, 0, "物料名称:", labelFont, addMaterialDialog);
        addComponent(gbc, 1, 0, nameField, textFieldFont, addMaterialDialog);
        
        // 规格型号输入
        JTextField specificationField = createTextField();
        addComponent(gbc, 0, 1, "规格型号:", labelFont, addMaterialDialog);
        addComponent(gbc, 1, 1, specificationField, textFieldFont, addMaterialDialog);
        
        // 单位输入
        JTextField unitField = createTextField();
        addComponent(gbc, 0, 2, "单位:", labelFont, addMaterialDialog);
        addComponent(gbc, 1, 2, unitField, textFieldFont, addMaterialDialog);
        
        // 存量输入
        JTextField stockField = createTextField();
        addComponent(gbc, 0, 3, "存量:", labelFont, addMaterialDialog);
        addComponent(gbc, 1, 3, stockField, textFieldFont, addMaterialDialog);
        
        // 备注输入
        JTextField remarkField = createTextField();
        addComponent(gbc, 0, 4, "备注:", labelFont, addMaterialDialog);
        addComponent(gbc, 1, 4, remarkField, textFieldFont, addMaterialDialog);
        
        // 提交按钮
        JButton submitButton = new JButton("提交");
        submitButton.setFont(new Font("微软雅黑", Font.BOLD, 16));
        submitButton.setBackground(Color.decode("#4CAF50"));
        submitButton.setForeground(Color.WHITE);
        submitButton.setFocusPainted(false);
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        addMaterialDialog.add(submitButton, gbc);
        
        // 提交按钮事件
        submitButton.addActionListener(e -> {
            // 输入校验
            if (nameField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(addMaterialDialog, "物料名称不能为空！", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (specificationField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(addMaterialDialog, "规格型号不能为空！", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            if (unitField.getText().trim().isEmpty()) {
                JOptionPane.showMessageDialog(addMaterialDialog, "单位不能为空！", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            // 校验存量
            String stockText = stockField.getText().trim();
            Long stock;
            
            String regex = "^[1-9]\\d*$"; // 正则表达式：匹配正整数
            
            if (stockText.isEmpty()) {
                stock = 0L; // 没输入存量时，默认设为 0
            } else {
                if (!stockText.matches(regex)) {
                    JOptionPane.showMessageDialog(addMaterialDialog, "存量必须为正整数！", "输入错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
                stock = Long.valueOf(stockText); // 转换为 Long 类型
            }
            
            
            // 收集输入数据并调用服务添加物料
            try {
                MaterialAddDTO newMaterial = MaterialAddDTO.builder()
                        .name(nameField.getText())
                        .specification(specificationField.getText())
                        .unit(unitField.getText())
                        .stock(stock) // 使用经过校验的存量
                        .remark(remarkField.getText())
                        .build();
                
                // 调用服务添加物料
                materialService.addMaterial(newMaterial);
                
                // 显示成功消息并刷新表格
                JOptionPane.showMessageDialog(addMaterialDialog, "物料添加成功！");
                freshTable(); // 刷新表格显示新添加的物料
                addMaterialDialog.dispose(); // 关闭对话框
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(addMaterialDialog, "添加物料失败：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
        addMaterialDialog.setVisible(true); // 显示对话框
    }
    
    private JTextField createTextField() {
        JTextField textField = new JTextField();
        textField.setPreferredSize(new Dimension(250, 30));
        textField.setFont(new Font("微软雅黑", Font.PLAIN, 16));
        return textField;
    }
    
    private void addComponent(GridBagConstraints gbc, int x, int y, String label, Font font, JDialog dialog) {
        gbc.gridx = x;
        gbc.gridy = y;
        JLabel jLabel = new JLabel(label);
        jLabel.setFont(font);
        dialog.add(jLabel, gbc);
    }
    
    private void addComponent(GridBagConstraints gbc, int x, int y, JComponent component, Font font, JDialog dialog) {
        gbc.gridx = x;
        gbc.gridy = y;
        component.setFont(font);
        dialog.add(component, gbc);
    }
}
